<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page  import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "java.util.Date" %>
<%@ page import = "java.text.SimpleDateFormat" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student File Detail</title>
<link rel="stylesheet" href="css/stylev2.css" />
<link rel="stylesheet" type="text/css" href="css/blue_button.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>

<link rel="stylesheet" href="css/redmond/jquery-ui.css" type="text/css"/>

<style type="text/css">
	a {
      text-decoration:none;
   }
</style>
	
<script>
function isValidUploadForm(oForm){
	
	//alert("Active isValidUploadForm");
	
	var _validFileExtensions = [".xlsx", ".xls",".doc",".docx",".pdf",".jpg",".jpeg",".png"];
	  var arrInputs = oForm.getElementsByTagName("input");
	 
	  
	//  alert("arrInputs:"+ oForm.getElementsByTagName("input")[0].value);
	  
	  var file_name =  oForm.getElementsByTagName("input")[0].value
	  	if(file_name=="")
	  	{
	  		alert("กรุณาเลือกไฟล์ที่จะทำการ Import ในรูปแบบ xls , xlsx , doc , docx , pdf , jpg , jpeg , png");
	  		return false;
	  	}
	  
	    for (var i = 0; i < arrInputs.length; i++) {
	        var oInput = arrInputs[i];
	        if (oInput.type == "file") {
	            var sFileName = oInput.value;
	            if (sFileName.length > 0) {
	                var blnValid = false;
	                for (var j = 0; j < _validFileExtensions.length; j++) {
	                    var sCurExtension = _validFileExtensions[j];
	                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
	                        blnValid = true;
	                        break;
	                    }
	                }

	                if (!blnValid) {
	                    alert("เกิดข้อผิดพลาด " + sFileName + " ไฟล์ที่แนบไม่ตรงรูปแบบของ : " + _validFileExtensions.join(", "));
	                    return false;
	                }
	            }
	        }
	    }

	    return true;

	
}


function SendBack(){


	var form = document.createElement("form");
	    form.setAttribute("method", "post");
	    form.setAttribute("action", "student_detail.jsp");
	    var hiddenField = document.createElement("input");
	    hiddenField.setAttribute("type", "hidden");
     hiddenField.setAttribute("name", "student_id");
     hiddenField.setAttribute("id","student_id");
     hiddenField.setAttribute("value", <%=request.getParameter("student_id")%>);
     form.appendChild(hiddenField);
     
     document.body.appendChild(form);
     form.submit();

}
function SendBackSamePage(){


	var form = document.createElement("form");
	    form.setAttribute("method", "post");
	    form.setAttribute("action", "student_file_all.jsp");
	    var hiddenField = document.createElement("input");
	    hiddenField.setAttribute("type", "hidden");
     hiddenField.setAttribute("name", "student_id");
     hiddenField.setAttribute("id","student_id");
     hiddenField.setAttribute("value", <%=request.getParameter("student_id")%>);
     form.appendChild(hiddenField);
     
     document.body.appendChild(form);
     form.submit();

}


function Delete_file(id,file_name)
{
	
	if (confirm("คุณต้องการจะลบไฟล์: " + file_name) == true) {
		 var file_id = id ;
		 var xmlhttp;
	
			
			if(window.XMLHttpRequest) {
				// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp = new XMLHttpRequest();
			}
			else {
				// code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			
			xmlhttp.onreadystatechange = function() {
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {	
					//alert("I'm Back");//////////////////
					
					var result = xmlhttp.responseText;
					//alert("result:"+result);
					if(result=="fail")
					{
						alert("ไม่สามารถทำการลบไฟล์ดังกล่าวได้");
					}
					else {
						
						alert("ลบไฟล์ดังกล่าวสำเร็จ");
						SendBackSamePage();
						
						
						
						
					}
					
					
				
				}// end if check state
			}// end function
			
			//alert("Before send :" + file_path);
			xmlhttp.open("POST", "student_file_all_delete_background.jsp?file_id="+file_id, true);
			xmlhttp.send();
	}else{}
	
}

</script>
<style type="text/css">

.silvergrad:hover {
 
    cursor: pointer;
   
}


</style>

</head>
<body>

<%
	// get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	

	// check session
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT	="0; URL=admin_home.jsp"> 	
	<%}
	

	
//////////get permission ///////////
	
	String name = String.valueOf(session.getAttribute("name"));
	String surname = String.valueOf(session.getAttribute("surname"));
	String role_name = String.valueOf(session.getAttribute("student_role"));
	
	String department_id = String.valueOf(session.getAttribute("department_id"));
	

	System.out.println("name : " + name);///////////////////////////////
	System.out.println("department_id : " + department_id);/////////////////////////
	
	
	
	List<String> system_name = new ArrayList<String>();
	
	Permission permission = new Permission(strUser,name);
	permission.setDepartmentId(department_id);
	permission.setStudentCreate(Boolean.valueOf(String.valueOf(session.getAttribute("student_create"))));
	permission.setStudentDelete(Boolean.valueOf(String.valueOf(session.getAttribute("student_delete"))));
	permission.setStudentRead(Boolean.valueOf(String.valueOf(session.getAttribute("student_read"))));
	permission.setStudentUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("student_update"))));
	
	String permiss = "";
	if(permission.getStudentCreate()) {
		permiss = permiss + "Add";
	}
	if(permission.getStudentUpdate()) {
		if("".equals(permiss)) {
			permiss = permiss + "Edit";
		} else {
			permiss = permiss + " Edit";
		}
	}
	if(permission.getStudentRead()) {
		if("".equals(permiss)) {
			permiss = permiss + "Read";
		} else {
			permiss = permiss + " Read";
		}
	}
	if(permission.getStudentDelete()) {
		if("".equals(permiss)) {
			permiss = permiss + "Delete";
		} else {
			permiss = permiss + " Delete";
		}
	}
	//check permission

	if(!permission.getStudentRead()){%>
		<script>alert("This user dont have PERMISSION to access this zone.");</script>
		<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_home.jsp"> 	
	<%}
	
	/*
	System.out.println("Reset message_path");
	session.setAttribute("message_path", "0");
	System.out.println("message_path:"+session.getAttribute("message_path"));
	*/
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
	} catch (Exception e) { 
		out.println(e);  
	}

	System.out.println("hostProperties : "+hostProps);////////////////try/////////////////
	System.out.println("usernameProperties : "+usernameProps);////////////////try/////////////////
	System.out.println("passwordProperties : "+passwordProps);////////////////try/////////////////
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/AIMS" +
				"?user=" + usernameProps  + "&password=" + passwordProps );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	String student_id = request.getParameter("student_id");
	System.out.println("@ student_file_all:"+student_id);
	
	if(student_id==null)
	{
		 response.sendRedirect("student_search.jsp");
	}
	

	
	String index="";
	Date date = new Date();
	int current_year = date.getYear()+1900+543;
	int current_month = date.getMonth()+1;
	Student stu = new Student();
	
	

	ResultSet rs = 
			connect.createStatement().executeQuery(" SELECT P.index , S.picture, N.title_th ,"+
					" N.name_th, N.surname_th , N.name_en , N.surname_en ,P.personal_id, P.gender,P.marital_status ,"+
				    " P.address , P.phone_number, P.email , P.facebook , S.father_name , S.father_address ,"+
					" S.father_phone ,S.mother_name , S.mother_address , S.mother_phone , S.parent_name,"+
				    " S.parent_address ,S.parent_phone ,S.student_id, S.start_date , S.entrance_id  , S.school ,"+
					" S.gpa , ST.status_name ,D.department_name_th, S.curriculum_id ,P.date_of_birth ,S.lecturer_id "+
				    " FROM student S, full_name N, department D, status ST, people P "+
				    " WHERE S.index = P.index AND P.full_name_id = N.full_name_id "+
				    " AND S.department_id = D.department_id AND S.status_id = ST.status_id "+
				    " AND S.student_id='"+student_id+"'");
	while(rs.next())
	{
		index = rs.getString("index");
		
		
		String src_path_full = rs.getString("picture");
		if((src_path_full!=null)&&(!("null").equals(src_path_full)))
		{
			String[] src_path_temp = src_path_full.split("/");	
			int length = src_path_temp.length;
			
			String src_path_a = src_path_temp[length-2];
			String src_path_b = src_path_temp[length-1];
			
			String src_path = src_path_a+"/"+src_path_b;
			
			stu.setPicture(src_path);
		
		}else{
			stu.setPicture("upload/default_person_icon.jpg");
			
		}
		
		
		stu.setNameTH(rs.getString("name_th"));
		stu.setSurnameTH(rs.getString("surname_th"));
		Date start_date = new SimpleDateFormat("yyyy-MM-dd").parse(rs.getString("start_date"));
		int start_date_num = start_date.getYear()+1900;
		String year_str ;
	
	
		if(current_month<6)
		{
			
			year_str =(current_year-start_date_num-543) + "";
			
		}else{
		
			year_str =(current_year-start_date_num+1-543)+"";
		}
		
		stu.setYear(year_str);
		stu.setDepartment(rs.getString("department_name_th"));
		stu.setStudentId(rs.getString("student_id"));
	}
	
	String sql_file = " SELECT index, file_path, name_old "+
			   " FROM file "+
			   " WHERE index='"+index+"'";

	System.out.println("sql_file:"+	sql_file);
	
	List<FileAll> file_list = new ArrayList<FileAll>();
	
	ResultSet rs_file = connect.createStatement().executeQuery(" SELECT `index`,file_id , file_path, name_old "+
															   " FROM file "+
															   " WHERE `index`='"+index+"'");
	
	while(rs_file.next())
	{
		FileAll file_temp = new FileAll();
		
		file_temp.setFileName(rs_file.getString("name_old"));
		file_temp.setFilePath(rs_file.getString("file_path"));
		file_temp.setIndex(rs_file.getString("index"));
		file_temp.setFileId(rs_file.getString("file_id"));
		
		file_list.add(file_temp);
		
	}
	
	System.out.println("file_list.size():"+file_list.size());
	
	
	/////////////////////////////////////////////////////

	connect.close();
%>


<div id="page-wrap">
		<div id="inside">
			<table border="1">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>	
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
			<table border="0">
				<tr style="font-size:10px">
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><h2><a href="student_home.jsp"><font color="#273b80"><label>หน้าแรก</label></font></a></h2></center>
					</td>
					<td width = "720" height="50" style= "background-color:#FFFFFF ; border-bottom-color: #FFFFFF;">
						<center><h2><font color="#273b80"><label>ค้นหา</label></font></h2></center>
					</td>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_summary.jsp"><h2><font color="#273b80"><label>สรุปจำนวนนักศึกษา</label></font></h2></a></center>
					</td>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_add.jsp"><h2><font color="#273b80"><label>เพิ่มนักศึกษา</label></font></h2></center>
					</td>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_edit.jsp"><h2><font color="#273b80"><label>แก้ไขข้อมูล</label></font></h2></a></center>
					</td>
				</tr>
			</table>	

				
					<div id="main-content-ac">
										</br></br>
					<div id="top-content" style="background-color: #e2e0e0;">
						</br></br>
							<center>
								<table  style="font-size:20px; background-color: #f2f0f0;" >
									<tr>
										<td width="50" height="10" rowspan="2" style="text-align: center;">
											 <% 
											  
											  	System.out.println("PICTURE:"+stu.getPicture());
												if(stu.getPicture()==null)
												{
														System.out.println(" PICTURE NULL");
											  %>
													 
											 			<img id="student_image" src="upload/default_person_icon.jpg" style="width:130px;height:160px;	">
											  <% 													
												}
												else{
													System.out.println(" PICTURE NOT NULL");
													
											   %>					
														 <img id="student_image" src="<%=stu.getPicture() %>" style="width:130px;height:160px;">
											   <%
												}
											  
											  %>		
										</td>
										 <td height="10">
									             	
									                	<%=stu.getNameTH()+" "+stu.getSurnameTH() %>					          		
									     </td>
									     <td height ="10">
									     			<%=stu.getDepartment() %>
									     </td>
									</tr>
									<tr>
										<td height="10">
													<%=stu.getStudentId() %>
										</td>
										 <td height="10">
									               ชั้นปี <%=stu.getYear() %>
									     </td>
										
									</tr>
								     
								</table>
							</center>
							</br></br>
					</div>
					<br><br>
					<div id="mid-content" style="background-color: #e2e0e0;">
						</br></br>
							<center>
								<div id="frm_add_file">
						
									<table style="font-size:20px; background-color: #f2f0f0;">
										<tr>
											<td>
												<center>
													 <form id="frm_upload" method="post" enctype="multipart/form-data" action="UploadServletStudentFileAll">
							        		  			 เลือกไฟล์ <input id="file_box" type="file" name="uploadFile"> 
							        		  			 <br>
							        		  			 <br>
							        		  			 <br>
							        		  			<input type="hidden" name="student_id" value="<%=stu.getStudentId() %>">
							        		  			<input type="submit" value="Add file">
							        		  			 
							        		  			 <br>
							        		  			 </form>
							        		  			 
							        		  	</center>
							        		 </td>
							        		 
					        		  		 
										</tr>
											
									</table>
									</br></br>
								</div>
							</center>
						
						
						
					</div>
						</br></br></br>
					<div id="bot-content" style="background-color: #e2e0e0;">
					
						</br></br></br>
					  <center>
					  	<%
					  		for(FileAll temp : file_list){
					  			
					  		%>
							<form id="<%=temp.getIndex() %>" method="get" action="DownloadServlet">
								<table style="background-color: #f2f0f0;">
									<tr>
										<td style="width:250px;">
											<input type="text" value="<%=temp.getFileName() %>" style="width:230px; height: 30px; font-size:15px;" readonly>
											<input type="hidden" id="file_path" name="file_path" value="<%=temp.getFilePath() %>">
											<input type="hidden" id="file_name" name= "file_name" value="<%=temp.getFileName() %>">
										</td>
										<td>
											<div style="cursor: pointer;">
										
												<input type="image" src="image/download_icon.png"  width="30px" height="30px">	
											</div>
											
										</td>
										
										<td>
											<div style="cursor: pointer;">
										
												<img src="image/delete_icon.png"  width="30px" height="30px" onCLick="Delete_file('<%=temp.getFileId() %>','<%=temp.getFileName() %>')">	
											</div>
										
										</td>
									</tr>
									
								</table>
							</form>
							<% 
					  		}
						%>
						</center>
						
						</br></br></br>
					
					</div>
					</br></br>
					<center>
					  			<button class="myButton" onClick="SendBack();">ย้อนกลับ</button>
					</center>
					</br></br></br></br>
		
				
				
			
			
			
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>
   </div>




</body>
</html>